<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');
session_start();

$action = $_GET['action'];

$cart	= new shoppingCart();

switch($action){	
	case "getcart":
		$cart->getCart();
		break;
}


class shoppingCart extends Controller
{
	public function __construct()
	{
		parent::__construct();
		header('Cache-Control: no-store, no-cache, must-revalidate');
		require_once('system/libraries/currency.php');
		$this->obj_currency = new Currency();
		if ($_SESSION['ORDER']['is_paypal_fast']){
			unset($_SESSION['ORDER']['is_paypal_fast']);
		}
	}
	
	public function getCart()
	{
		$items = $_SESSION['cart'];
		
		//print_r($items);exit;
		$itemHTML = "";
		
		if(empty($items) || (count($items) == 1 && $items['sessionID'])){
			if ($this->Input->get('action') && $this->Input->get('action') == 'movewishlist')
			{
				$itemHTML .= "<p>Item(s) has been moved to your <a href=\"backpocket.html\" title=\"WISHLIST\"><u>WISHLIST</u></a>.</p>";
			}
			else
			{
				$itemHTML .= "<p>There is no products in your shopping cart.You can continue shopping <a href=\"" . $this->Environment->base . "\" title=\"daftshopping\"><u>here</u></a></p>";
			}
			unset($_SESSION['cart']['sessionID']);
		}else{
			$totalPrice = 0;
			foreach ($items as $key => $item) {
				if ($key == 'sessionID')
					continue;
				//print_r($item);
				$totalPrice += number_format(floatval($item['price']*$item['quantity'])+$item['gwPrice'], 2, '.', '');
				$itemHTML .= '<script type="text/javascript">
								function changeColor(node)
								{
									jQuery("#cart_out_of_stock").hide();
									jQuery(".item_success").hide();
									jQuery.ajax({
											 type: "POST",
											 url: "changeShopingCart.php",
											 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'colour\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val(),
											 success: function(msg){ 
												//alert( "Data Saved: " +   msg );
												if (msg != \'false\')
												{
													//var objHtml = {"method": "newURI"};
													var objHtml = eval(msg);
													//alert(objHtml[0].td_skin);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);
													
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").hide();
												}
												else
												{
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").show();
												}
											} 
										});
								}
								
								function changeSize(node)
								{
									jQuery("#cart_out_of_stock").hide();
									jQuery(".item_success").hide();
									jQuery.ajax({
											 type: "POST",
											 url: "changeShopingCart.php",
											 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'colour\']").val() + "&size=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val(),
											 success: function(msg){ 
												//alert( "Data Saved: " +   msg );
												if (msg != \'false\')
												{
													//var objHtml = {"method": "newURI"};
													var objHtml = eval(msg);
													//alert(objHtml[0].td_skin);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);
													
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").hide();
												}
												else
												{
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").show();
												}
											} 
										});
								}
								
								function changeQuantity(node)
								{
									jQuery("#cart_out_of_stock").hide();
									jQuery(".item_success").hide();
									jQuery.ajax({
											 type: "POST",
											 url: "changeShopingCart.php",
											 data: "FORM_SUBMIT=changeCart&color=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'colour\']").val() + "&size=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val() + "&quantity=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'size_ids\']").val(),
											 success: function(msg){ 
												//alert( "Data Saved: " +   msg );
												if (msg != \'false\')
												{
													//var objHtml = {"method": "newURI"};
													var objHtml = eval(msg);
													//alert(objHtml[0].td_skin);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("table.cart_item td.td_info").html(objHtml[0].td_info);
													jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("div.skin").html(objHtml[0].td_skin);													
													
													
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").hide();
												}
												else
												{
													//jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("#cart_out_of_stock").show();
												}
											} 
										});
								}
								
								function fn_updated_Cart(node)
								{
									jQuery("#cart_out_of_stock").hide();
									jQuery(".item_success").hide();
									jQuery("#updated_img").html("UPDATE CART");
									jQuery("#updated_img").attr("class", "update updateCart");
									jQuery.ajax({
										 type: "POST",
										 url: "changeShopingCart.php",
										 data: "FORM_SUBMIT=UpdateCart&id_catalog=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'id\']").val() + "&session_id=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'colour\']").val() + "&size=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'size\']").val() + "&quantity=" + jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("select[@name=\'quantity\']").val(),
										 success: function(msg){ 
											//alert( "Data Saved: " +   msg );
											var arrMsg = msg.split(\'::\');
											var arrStatus = arrMsg[0].split(\'=\');
											var arrStock = arrMsg[1].split(\'=\');
											var arrTotal = arrMsg[2].split(\'=\');
											var arrSession_id = arrMsg[3].split(\'=\');
											var merge = arrMsg[4].split(\'=\');
											
											if (arrStatus[0] == \'failure\')
											{
												alert("Update failure!");
												jQuery(node).parent().parent().parent().parent().parent().parent().parent().find(".item_success").hide();
											}
											else
											{
												jQuery(node).parent().parent().parent().parent().parent().parent().parent().find(".item_success").show();
												jQuery(".cart").html("Shopping Cart(" + arrStock[1] + ")");
												var old_total_price = jQuery(node).parent().parent().parent().parent().parent().find(".unit_price strong").html().substring(4, jQuery(node).parent().parent().parent().parent().parent().find(".unit_price strong").html().length-1);
												var increase = arrTotal[1] - old_total_price;
												var _currency_code = jQuery("input[@name=\'currency_code\']").val();
												jQuery(node).parent().parent().parent().parent().parent().find(".unit_price strong").html(_currency_code + arrTotal[1]);
												jQuery(node).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val(arrSession_id[1]);
												
												var checkout_old_total = jQuery("form[@name=\'checkoutfrom\']").find("div.total_price span#total_cost").html();
												var checkout_total = Math.round((parseFloat(checkout_old_total) + parseFloat(increase))*Math.pow(10, 2))/Math.pow(10, 2);
												checkout_total += "";
												if (checkout_total.indexOf(".") <= -1)
													checkout_total = checkout_total + ".00";
												//alert(checkout_total);
												jQuery("form[@name=\'checkoutfrom\']").find("div.total_price span#total_cost").html(checkout_total);
												jQuery("form[@name=\'checkoutfrom\']").find("input[@name=\'totalPrice\']").val(checkout_total);
											}
											
											if (merge[1] == \'true\')
											{
												var strUrl = window.location.href + "";
												if (strUrl.indexOf("?") > -1)
													strUrl = strUrl.substring(0, strUrl.indexOf("?"));
												strUrl += "?updated=success&session_id=" + arrSession_id[1];
												window.location.href = strUrl;
											}
										} 
									});
									
									return false;
								}
							</script>
				' . $this->getItem($item['id'], $item['skuid'], $item['name'], $item['price'], $item['colour'], $item['size'], $item['quantity'], $item['colour_ids'], $item['size_ids'], intval($item['gift_wrapping']), $item['gwPrice']);
			}
			
			$totalPrice = number_format(floatval($totalPrice), 2, '.', '');
			$_SESSION['ORDER']['totalPrice'] = $totalPrice;
			$itemHTML .= $this->setTotal($totalPrice);
		}
		
		echo $itemHTML;
	}

	public function getItem($id,$skuid,$name,$price,$colour,$size,$quantity,$colour_ids,$size_ids, $is_wrapping=0, $gwPrice)
	{
		//print_r($_SESSION['cart']);
		
		$is_noneStock = false;
		$is_overStock = false;
		
		// Judge the update information
		if ($this->Input->get('updated'))
		{
			switch ($this->Input->get('updated'))
			{
				case 'success':
					break;
				case 'failure':
					if (!$this->Input->get('stock'))
						$is_noneStock = true;
					else
						$is_overStock = true;
					break;
				default:
					break;
			}
		}
		
		$this->import("Database");
		$objCataColor = $this->Database->prepare("SELECT `id` FROM `catalog_colour` WHERE `title`=?")
										->execute($colour);
		$id_color = $objCataColor->id;
		
		$strStockInfo = $this->getCurrentStockInfo($id, $colour, $size);
		// Stock information deal with.
		if (is_null($strStockInfo))
		{
			return "";
		}
		elseif (!$strStockInfo)
		{
			$is_noneStock = true;
		}
		else 
		{
			$is_noneStock = false;
			if (intval($quantity) > $strStockInfo)
			{
				$quantity = $strStockInfo;
				$is_overStock = true;
			}
			else 
				$is_overStock = false;
		}
		
		$imgPath = "daft_files/catalog/products/$skuid/$colour/1.jpg";
		
		$sessionID	= $id."_".$size."_".trim(strtolower($colour));
		$formName = "itemform_" . $sessionID;
		
		// Get catalog information.
		$objCatalog = $this->Database->prepare("SELECT `category` FROM `product_catalog` WHERE `id`=?")
									->execute($id, time(), time());
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
										->execute(time());
		
		$itemHTML = '<script type="text/javascript">
			jQuery(function(){
				jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'colour\']").change(function(){
					//jQuery("form[name=\'' .$formName . '\']").submit();
					jQuery("#cart_out_of_stock").hide();
					jQuery(".item_success").hide();
					jQuery.ajax({
						 type: "POST",
						 url: "changeShopingCart.php",
						 data: "FORM_SUBMIT=changeCart&color=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'colour\']").val() + "&session_id=" + jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'size_ids\']").val(),
						 success: function(msg){ 
							//alert( "Data Saved: " +   msg );
							if (msg != \'false\')
							{
								//var objHtml = {"method": "newURI"};
								var objHtml = eval(msg);
								//alert(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("div.skin").html(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").hide();
							}
							else
							{
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").show();
							}
						} 
					});
				});
				jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'size\']").change(function(){
					//jQuery("form[name=\'' .$formName . '\']").submit();
					jQuery("#cart_out_of_stock").hide();
					jQuery(".item_success").hide();
					jQuery.ajax({
						 type: "POST",
						 url: "changeShopingCart.php",
						 data: "FORM_SUBMIT=changeCart&size=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'size\']").val() + "&color=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'colour\']").val() + "&session_id=" + jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'size_ids\']").val(),
						 success: function(msg){ 
							//alert( "Data Saved: " +   msg );
							if (msg != \'false\')
							{
								//var objHtml = {"method": "newURI"};
								var objHtml = eval(msg);
								//alert(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("div.skin").html(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").hide();
							}
							else
							{
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").show();
							}
						} 
					});
				});
				jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'quantity\']").change(function(){
					//jQuery("form[name=\'' .$formName . '\']").submit();
					jQuery("#cart_out_of_stock").hide();
					jQuery(".item_success").hide();
					jQuery.ajax({
						 type: "POST",
						 url: "changeShopingCart.php",
						 data: "FORM_SUBMIT=changeCart&size=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'size\']").val() + "&color=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'colour\']").val() + "&quantity=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'quantity\']").val() + "&session_id=" + jQuery(this).parent().parent().parent().parent().parent().parent().parent().find("input[@name=\'session_id\']").val() + "&colour_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'colour_ids\']").val() + "&size_ids=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'size_ids\']").val(),
						 success: function(msg){ 
							//alert( "Data Saved: " +   msg );
							if (msg != \'false\')
							{
								//var objHtml = {"method": "newURI"};
								var objHtml = eval(msg);
								//alert(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("div.skin").html(objHtml[0].td_skin);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_pic").html(objHtml[0].td_pic);
								jQuery("form[name=\'' .$formName . '\']").find("table.cart_item td.td_info").html(objHtml[0].td_info);
								
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").hide();
							}
							else
							{
								//jQuery("form[name=\'' .$formName . '\']").find("#cart_out_of_stock").show();
							}
						} 
					});
				});
				
				jQuery("form[name=\'' .$formName . '\']").find("a.updateCart").click(function(){
					jQuery("#cart_out_of_stock").hide();
					jQuery(".item_success").hide();
					jQuery.ajax({
						 type: "POST",
						 url: "changeShopingCart.php",
						 data: "FORM_SUBMIT=UpdateCart&id_catalog=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'id\']").val() + "&session_id=" + jQuery("form[name=\'' .$formName . '\']").find("input[@name=\'session_id\']").val() + "&colour=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'colour\']").val() + "&size=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'size\']").val() + "&quantity=" + jQuery("form[name=\'' .$formName . '\']").find("select[@name=\'quantity\']").val(),
						 success: function(msg){
							if (msg != undefined && msg != "")
							{
								var arrMsg = msg.split(\'::\');
								var arrStatus = arrMsg[0].split(\'=\');
								var arrStock = arrMsg[1].split(\'=\');
								
								if (arrStatus[0] == \'failure\')
								{
									alert("Update failure!");
									jQuery("form[name=\'' .$formName . '\']").find(".item_success").hide();
								}
								else
								{
									jQuery("form[name=\'' .$formName . '\']").find(".item_success").show();
									jQuery(".cart").html("Shopping Cart(" + arrStock[1] + ")");
								}
							}
						} 
					});
					
					return false;
				});
			});
		</script>
		<form action="product.html" method="post" name="'.$formName.'">
		<div class="item_success success" ' . (($this->Input->get('updated') == 'success' && $this->Input->get('session_id') == $sessionID) ? '' : 'style="display:none;"') . '>Your shopping cart is updated.</div>
		<div class="error"' . ((!$is_noneStock) ? ' style="display:none;"' : '') . ' id="cart_out_of_stock">The quantity of this product is out of stock. Please select again.</div>
		<div class="error"' . ((!$is_overStock) ? ' style="display:none;"' : '') . ' id="cart_over_stock">The quantity of current product has overd the stock. Please select another product.</div>
		<input type="hidden" value="updatecart" name="FORM_SUBMIT"/>
		<input type="hidden" name="session_id" value="'.$sessionID.'"/>
		<input type="hidden" name="colour_ids" value="' . $colour_ids . '" />
		<input type="hidden" name="size_ids" value="' . $size_ids . '" />
		<input type="hidden" value="'.$id.'" name="id"/>
		<input type="hidden" value="'.$obj_currency->sign.'" name="currency_code" />
		<table class="cart_item">
			<tr>
				<td rowspan="2" class="td_pic"><a href="./product.html?category='.$objCatalog->category.'&id='.$id.'&id_colour=' . $id_color . '&id_size=' . $size . '"><img src="image.php?src='.$imgPath.'&width=79&height=79" alt="'.$name.'" /></a></td>
				<td class="td_info">
					<h4><a href="./product.html?category='.$objCatalog->category.'&id='.$id.'&id_colour=' . $id_color . '&id_size=' . $size . '">'.$name.'</a></h4>
					<small>#'.$skuid.'</small><br/>
					<small>' . $this->obj_currency->change_order(number_format($price, 2, '.', '')) . '</small>' . (($is_wrapping) ? '<br /><small>GIFT WRAPPING ' . $this->obj_currency->change_order($gwPrice) . '</small>' : '') . (($is_noneStock) ? '<br /><span class="error">Out of stock - Please remove from your cart.</span>' : '') . '
				</td>
				<td rowspan="2" class="td_skin">
					<div class="skin">
						<p>
							<label>COLOR</label>
							<select name="colour" class="color">
								'.$this->setColour($colour,$colour_ids).'
							</select>' . ((!$is_noneStock && !$is_overStock) ? ' 
							<a href="#" title="UPDATE CART" class="update updateCart">UPDATE CART</a>' : '') . '
						</p>
						<p>
							<label>SIZE</label>
							<select name="size" class="size">
								'.$this->setSize($size,$size_ids).'
							</select>
							<a href="product.html?FORM_SUBMIT=removetobackpocket&sessionID='.$sessionID.'" title="" class="update">MOVE TO WISHLIST</a>
						</p>
						<p>
							<label>QUANTITY</label>
							' . (($is_noneStock) ? '' : '
							<select name="quantity" class="color">
								'.$this->setQuantity($quantity, $strStockInfo).'
							</select>') . '
							<a href="product.html?FORM_SUBMIT=removefromcart&sessionID='.$sessionID.'" title="REMOVE FROM CART" class="update">REMOVE FROM CART</a>
						</p>
					</div>
				</td>
				<td rowspan="2" class="unit_price"><strong>'. $this->obj_currency->change_order($this->setPrice($price, $quantity, $gwPrice)) .'</strong></td>
			</tr>
			<tr><td class="error"></td></tr>
		</table>
		</form>
		';	
		
		return $itemHTML;
	}

	public function getColour()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_colour` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['title'] = $objRd->title;
		}
		return $dataArray;
	}	

	public function getSize()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_size` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['size'] = $objRd->size;
		}
		return $dataArray;
	}	
	
	public function setColour($colour,$colour_ids)
	{
		$colourList = $this->getColour();
		$colours = explode(",", $colour_ids);
		
		$strHTML = "";
		for($i=0;$i<count($colours);$i++){
			$key  	  = $colours[$i];
			$selected = ($colour == $colourList[$key]['title']) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$colourList[$key]['title'].'" '.$selected.'>'.$colourList[$key]['title'].'</option>\n';
		}
		
		return $strHTML;
	}
	
	public function setSize($size,$size_ids)
	{
		$sizeList	= $this->getSize();
		$sizes		= explode(",", $size_ids);
		
		$strHTML = "";
		for($i=0;$i<count($sizes);$i++){
			$key  	  = $sizes[$i];
			$selected = ($size == $key) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$key.'" '.$selected.'>'.$sizeList[$key]['size'].'</option>\n';
		}
		
		return $strHTML;
	}	
	
	/**
	 * This function get the stock of this special product and current quantity.
	 * @param int $id_catalog
	 * @param string $colour
	 * @param int $size
	 * @return int currentStock
	 */
	public function getCurrentStockInfo($id_catalog=0, $colour=0, $size=0)
	{
		if (!$id_catalog || !$colour || !$size)
			return null;
		// Get the colour id.
		$this->import("Database");
		$strSQL = "SELECT `id` FROM `catalog_colour` WHERE `title`=?";
		$objId_colour = $this->Database->prepare($strSQL)
							->execute($colour, time(), time());
		
		if ($objId_colour->numRows < 1)
			return null;
		
		$id_colour = $objId_colour->id;
		
		// Get the stock of this special product.
		$strSQL = "SELECT * FROM `tl_catalog_attribute` WHERE `id_catalog`=? AND `id_color`=? AND `id_size`=?";
		$objSock = $this->Database->prepare($strSQL)
								->execute($id_catalog, $id_colour, $size);
		if ($objSock->numRows < 1)
			return null;
		
		$cnt_stock = intval($objSock->catalog_stock);
		
		return $cnt_stock;
	}
	
	/**
	 * This function generate the html of quantity
	 * @param int $quantity
	 * @param int $cntStock
	 * @return string html
	 */
	public function setQuantity($quantity, $cntStock=0)
	{
		if (!$quantity || !$cntStock)
			return "";
			
		if ($quantity > $cntStock)
			$quantity = $cntStock;
		
		$strHTML = "";
		for($i=1;$i<=$cntStock;$i++){
			$selected = ($i == $quantity) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>\n';
		}
		
		return $strHTML;
	}	

	public function setPrice($price, $quantity, $gwPrice)
	{
		$strHTML = number_format($price*$quantity+$gwPrice, 2, '.', '');
		
		return $strHTML;
	}

	public function setTotal($totalPrice)
	{
		// Get shippings from database.
		$this->import("Database");
		
		/** Get the shop currency **/
		$is_ec_paypal = false; 
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
										->execute(time());
		if ($obj_currency->iso_code != 'cn')
			$is_ec_paypal = true;
		
		if ($_COOKIE['FE_USER_AUTH'])
		{
			$ec_link = $this->Environment->base . 'ecpaypal.php?action=revieworder';
		}
		else
		{
			$ec_link = $this->Environment->base . 'sign-in.html?referer='.base64_encode('ecpaypal.php?action=revieworder');
		}
		$strHTML = '
		<script type="text/javascript">
			jQuery(function(){
				jQuery("#post").click(function(e){
					var el = e.target || e, totalPrice = 0, shippingPrice = 0;
					jQuery(".post_price span#shipping_cost").html(el.value);
					
					if ($("input[@name=totalPrice]").val() != undefined)
					{
						totalPrice = parseFloat($("input[@name=totalPrice]").val()); 
						shippingPrice = parseFloat($("input[@name=shipping][@checked]").val()); 
						$("#total_cost").html((totalPrice+shippingPrice).toFixed(2));
					}
					
					jQuery("input[@name=\'id_carrier\']").val($("input[@name=shipping][@checked]").parent("td").find("input[@type=hidden]").val());
				});
				jQuery("#paypal_express").click(function(e){';
		if (!$_COOKIE['FE_USER_AUTH'])
			$strHTML .= 'if (confirm("Please login first!")) return true; else return false;';
			
		$strHTML .= '
					jQuery("#paypal_express").attr("href", jQuery("#paypal_express").attr("href")+"&totalPrice="+jQuery("input[@name=\'totalPrice\']").val()); 
					return true;
				});
			});
		</script>
		<form name="checkoutfrom" method="post" action="address.html">
		<input type="hidden" name="totalPrice" value="'.$totalPrice.'"/>		
		<!-- voucher
		<div id="voucher">
			<table>
				<tr>
					<td class="td1">I HAVE A GIFT VOUCHER: <input type="text" name="voucher" class="text" value="enter you code here"  onfocus="if (this.value == \'enter you code here\') {this.value = \'\';}" onblur="if (this.value == \'\'){this.value = \'enter you code here\'; }" />
					<td class="td2">- RMB 50</td>
				</tr>
			</table>
		</div>  
		-->
		
		<div class="total_price">
			<small>TOTAL //</small>
			<span><span id="total_cost">' . $this->obj_currency->change_order(number_format(($totalPrice), 2, '.', '')) . '</span></span>
		
		</div> <!-- total_price end -->
		<p class="submits"><a href="./" title="CONTINUE SHOPPING">CONTINUE SHOPPING</a><input type="submit" name="submit" class="submit" value="CHECKOUT" />' . (($is_ec_paypal) ? '<a href="'.$ec_link.'" id="paypal_express"><img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"></a>' : '') . '</p>
		</form>';
		return $strHTML;
	}	
}
?>